SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

CREATE PROCEDURE [dbo].[DnnProduct_CDS_TemplatesList]
	@DistributorID varchar(50),
	@SortExpression varchar(100),
	@MaximumRows int = null, 
	@StartRowIndex int = null
AS
BEGIN
	SET NOCOUNT ON;

	DECLARE @SQLString NVARCHAR(1000)
	DECLARE @ParmDefinition NVARCHAR(100)

	/* Build the SQL string once.*/
	SET @SQLString = N'WITH ItemRN AS (SELECT ROW_NUMBER() OVER(ORDER BY '+ @SortExpression + ') AS RowNum, [ID], DistributorID, [Name], [Description], [Default], [Type] FROM [DnnProduct_CDS_Templates] where DistributorID = @DistributorID )'

	SET @SQLString = @SQLString + N' SELECT [ID], DistributorID, [Name], [Description], [Default], [Type] FROM ItemRN WHERE RowNum BETWEEN @startRowIndex+1 AND (@startRowIndex+@maximumRows);'
	SET @ParmDefinition = N'@MaximumRows int, @StartRowIndex int, @DistributorID varchar(50)'
	EXECUTE sp_executesql @SQLString, @ParmDefinition, @MaximumRows, @StartRowIndex, @DistributorID
END
GO
